<template>
	<NavBar icon="left" :title="`${form.addressId ? '编辑我的地址' : '添加我的地址'}`" />
	<view class="contain bg-[#f2f2f2] p-2 ">
		<view class="bg-white rounded-md p-2 ">
			<uv-form labelWidth="100" labelPosition="left" :model="form" :rules="rules" ref="formDom">
				<uv-form-item label="目的地区:" prop="oldPassword" borderBottom>
					<view @click="openPicker('countryId')">
						<text class="text-[#c4c7d3] ml-1">
						<text class="text-[black]" v-if="form.country" >{{form.country}}</text>
						 <text v-else>请选择目的地</text> </text><uv-icon
							name="arrow-down" class="float-right ml-2" color="#c4c7d3"></uv-icon>
					</view>
				</uv-form-item><uv-form-item label="省份:" prop="newPassword" borderBottom>
					<view @click="openPicker('provinceId')">
						<text class="text-[#c4c7d3] ml-1">
						<text class="text-[black]" v-if="form.province "> {{form.province  }}</text>
						<text v-else> 请选择省</text> 
						</text><uv-icon
							name="arrow-down" class="float-right ml-2" color="#c4c7d3"></uv-icon> 
					</view>
				</uv-form-item>
				<uv-form-item label="直辖市/县:" prop="reNewPassword" borderBottom>
					<view @click="openPicker('cityId')">
						<text class="text-[#c4c7d3] ml-1">
						<text class="text-[black]" v-if="form.city"> {{form.city }}</text>
						<text v-else>请选择市 </text> </text><uv-icon name="arrow-down"
							class="float-right ml-2" color="#c4c7d3"></uv-icon>
					</view> 
				</uv-form-item>
				<uv-form-item label="直辖市/区:" prop="reNewPassword" borderBottom>
					<view @click="openPicker('regionId')">  
						<text class="text-[#c4c7d3] ml-1">
						<text class="text-[black]" v-if="form.region"> {{ form.region}}</text>
						<text v-else> 请选择区</text> </text><uv-icon name="arrow-down"
							class="float-right ml-2" color="#c4c7d3"></uv-icon>
					</view>
				</uv-form-item>
				<uv-form-item label="姓名:" prop="contactName" borderBottom>
					<uv-input  placeholder="请填写名字" v-model="form.contactName" border="none">
					</uv-input>
				</uv-form-item>
				<uv-form-item label="电话" prop="contactPhone" borderBottom>
					<uv-input  placeholder="请填写电话" v-model="form.contactPhone" border="none">
					</uv-input>
				</uv-form-item>
				<uv-form-item label="手机号:" prop="phone" borderBottom>
					<uv-input  placeholder="请填写手机号" v-model="form.phone" border="none">
					</uv-input>
				</uv-form-item>
				<uv-form-item label="邮编:" prop="emsCode" borderBottom>
					<uv-input  placeholder="请填写邮编" v-model="form.emsCode" border="none">
					</uv-input>
				</uv-form-item>
				<uv-form-item label="收货地址:" prop="address" borderBottom>
					<uv-input  placeholder="请填写收货地址" v-model="form.address" border="none">
					</uv-input>
				</uv-form-item>
			</uv-form>
		</view>
		<uv-button class="mt-2" type="primary" text="提交" customStyle="margin-top: 10px" @click="submit"></uv-button>
	</view>

	<!-- 选择器 -->
	<uv-picker activeColor="#3c9cff" @close="close" :loading="loadingShow" @change="choose" ref="picker" :columns="columns" @confirm="confirm">
	 </uv-picker>
</template>

<script setup>
	import store from '@/store/index.js'
	import * as api from '@/api/modules/address.js'
import { watch } from 'vue';

	const form = ref({
		countryId: '',
		country: '',
		provinceId: '',
		province: '',
		cityId: '',
		city: '',
		regionId: '',
		region: '',
		userId: store().user.userInfo.userId,
		contactName: '',
		contactPhone: '', 
		phone:'',//手机号
		emsCode: '',
		address: ''
	})
	const formDom = ref()
	form.value.userId = store().user.userInfo.userId
	// 校验规则
	const rules = {
		address:{
				type: 'string',
				required: true,
				message: '请填写地址',
				trigger: ['blur' ]
			},
		emsCode:[{
				type: 'string',
				required: true,
				message: '请填写邮编',
				trigger: ['blur' ]
			},
			{
				validator: (rule, value, callback) => {
					const reg = /^(0[1-7]|1[0-356]|2[0-7]|3[0-6]|4[0-7]|5[1-7]|6[1-7]|7[0-5]|8[013-6])\d{4}$/
					return reg.test(value)
				},
				message: '请填写正确的邮编',
				trigger: ['blur']
			}],
		contactPhone:[{
				type: 'string',
				required: true,
				message: '请填写手机号',
				trigger: ['blur' ]
			},
			{
				validator: (rule, value, callback) => {
					const reg = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/
					return reg.test(value)
				},
				message: '请填写正确的手机号',
				trigger: ['blur']
			}], 
			phone:[{
				type: 'string',
				required: true,
				message: '请填写电话',
				trigger: ['blur' ]
			},
			{
				validator: (rule, value, callback) => {
					const reg = /^(?:(?:\d{3}-)?\d{8}|^(?:\d{4}-)?\d{7,8})(?:-\d+)?$/
					return reg.test(value)
				},
				message: '请填写正确的电话',
				trigger: ['blur']
			}], 
	}
	const submit = () => { 
		// 国家省市县必填
		if(!form.value.countryId || !form.value.provinceId || !form.value.cityId || !form.value.regionId) return uni.showToast({
			title:'目的地区、省、市、县为必填项',
			icon:'none'
		})
		formDom.value.validate().then(async _ => {  
		if(!form.value.addressId){	
			await api.addAddressAPI(form.value)
		}else{
				await api.editAddressAPI(form.value)
			}
			uni.showToast({
				title:form.addressId ? '编辑地址成功' : '新增地址成功' ,
				icon:'none'
			})
			uni.navigateTo({
				url:'/pages/admin/address/address'
			})
		}).catch((err) => {
			console.log('出错了',err)
		})
	}
	// <!-- 选择器 -->
	const columns = ref([
		[]
	])
	const choose = e => {
		console.log(e, 9);
		console.log(e.index, 9);
	}
	const picker = ref()
	const currentOpt = ref('') //控制pick组件的要渲染哪个数据
	let countryList = []
	let provinceList = []
	let cityList = []
	let regionList = []
	const loadingShow = ref(true)
	const openPicker = async (opt) => {
		picker.value.open() 
		switch (opt) {
			case 'countryId':
				await getCountryList()
				columns.value = countryList 
		// loadingShow.value = false
				break;
			case 'provinceId':
				if (!form.value.countryId) {
					return uni.showToast({
						title: '请先选择国家',
						icon: 'none'
					})
				}
				columns.value = provinceList
				break;
			case 'cityId':
				if (!form.value.provinceId) {
					return uni.showToast({
						title: '请先选择省份',
						icon: 'none'
					})
				}
				columns.value = cityList
				break;
			default:
				if (!form.value.cityId) {
					return uni.showToast({
						title: '请先选择城市',
						icon: 'none'
					})
				}
			columns.value = regionList
		}
		loadingShow.value = false
		currentOpt.value = opt
	}
	const close = ()=>{
		if(!form.value[currentOpt.value]) uni.showToast({
			title:'此项必填',
			icon:'none'
		})
	}
	const confirm = (e) => {
		form.value[currentOpt.value] = e.value[0].value
		switch (currentOpt.value) {
			case 'countryId':
				form.value.country = e.value[0].text
				break;
			case 'provinceId':
				form.value.province = e.value[0].text
				break;
			case 'cityId':
				form.value.city = e.value[0].text
				break;
			default:
				form.value.region = e.value[0].text
		}
	}
	
	watch(()=>form.value.countryId, async value =>{
		form.value.province = ''
		form.value.provinceId = '' 
		if(!value) return   
		await getProvinceList()
	})
	watch(()=>form.value.provinceId,async value =>{
		form.value.city = ''
		form.value.cityId = '' 
		if(!value) return  
		await getCityList()
	})
	watch(()=>form.value.cityId,async value =>{
		form.value.region = ''
		form.value.regionId = ''
		if(!value) return  
		await getRegionList()
	}) 
	// 获取国家 省 市 县 数据
	const getCountryList = async value  => {
		const {
			rows
		} = await api.countryListAPI()
		countryList  = [rows.map(item => {
			return {
				text: item.destinationName,
				value: item.destinationId
			}
		})]
	}
	const getProvinceList = async () => {
		const {
			data
		} = await api.provinceListAPI(form.value.countryId)
		provinceList  = [data.map(item => {
			return {
				text: item.areaName,
				value: item.id
			}
		})]
	}

	const getCityList = async () => {
		const {
			data
		} = await api.cityListAPI(form.value.provinceId)
		cityList  = [data.map(item => {
			return {
				text: item.areaName,
				value: item.id
			}
		})]
	}
	const getRegionList = async () => {
		const {
			data
		} = await api.regionListAPI(form.value.cityId)
		regionList  = [data.map(item => {
			return {
				text: item.areaName,
				value: item.id
			}
		})]
	}
	
	// 接收ID
	onMounted(() => {
		const instance = getCurrentInstance().proxy
		const eventChannel = instance.getOpenerEventChannel(); 
		eventChannel.on('edit', function(data) {  
			console.log(1,data);
			form.value = {...data.addressInfo}
		})
	})
</script>
<style lang="scss">
.contain {
		height: calc(100vh - 44px)
		}
</style>